package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.EpisodeExcelDTO;
import com.laijiale.dto.EpisodeInsertDTO;
import com.laijiale.dto.EpisodePageDTO;
import com.laijiale.dto.EpisodeUpdateDTO;
import com.laijiale.entity.Category;
import com.laijiale.entity.Course;
import com.laijiale.entity.Season;
import com.laijiale.exception.ServiceException;
import com.laijiale.result.Result;
import com.laijiale.until.MinioUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Episode;
import com.laijiale.mapper.EpisodeMapper;
import com.laijiale.service.EpisodeService;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vo.EpisodeSimpleListVO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.EpisodeTableDef.EPISODE;

/**
 * 集次表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "episode")
public class EpisodeServiceImpl extends ServiceImpl<EpisodeMapper, Episode>  implements EpisodeService{

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(EpisodeInsertDTO dto) {
        //标题查重
        if (QueryChain.of(mapper).where(EPISODE.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("集次标题已存在");
        }
        //组装 entity 实体类
        Episode episode= BeanUtil.copyProperties(dto,Episode.class);
        episode.setVideo(ML.Episode.DEFAULT_VIDEO);
        episode.setCover(ML.Episode.DEFAULT_VIDEO_COVER);
        episode.setCreated(LocalDateTime.now());
        episode.setUpdated(LocalDateTime.now());
        return mapper.insert(episode)>0;
    }
    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Episode select(Long id) {
        RelationManager.addQueryRelations("season");
        return mapper.selectOneWithRelationsById(id);
    }
    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<EpisodeSimpleListVO> simpleList() {
        return QueryChain.of(mapper).orderBy(EPISODE.IDX.asc(),EPISODE.ID.desc())
                .withRelations().listAs(EpisodeSimpleListVO.class);
    }
    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition ="#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Episode> page(EpisodePageDTO dto) {
        RelationManager.addQueryRelations("season");
        QueryChain<Episode> queryChain=QueryChain.of(mapper).orderBy(EPISODE.IDX.asc(),EPISODE.ID.desc());
        //title条件
        String title =dto.getTitle();
        if (ObjectUtil.isNotNull(title)){
            queryChain.where(EPISODE.TITLE.like(title));
        }
        //seasonId条件
        Long seasonId =dto.getFkSeasonId();
        if (ObjectUtil.isNotNull(seasonId)){
            queryChain.where(EPISODE.FK_SEASON_ID.eq(seasonId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(),dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(EpisodeUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper).
                where(EPISODE.TITLE.eq(dto.getTitle()))
                .and(EPISODE.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("集次标题已存在");
        }
        // 组装 entity 实体类
        Episode episode = BeanUtil.copyProperties(dto, Episode.class);
        // 设置 entity 默认值
        episode.setUpdated(LocalDateTime.now());
        return UpdateChain.of(episode).where(EPISODE.ID.eq(episode.getId())).update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return UpdateChain.of(mapper).where(EPISODE.ID.eq(id)).remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return UpdateChain.of(mapper).where(EPISODE.ID.in(ids)).remove();
    }

    @Override
    @CacheEvict(allEntries = true)
    public Result<String> uploadVideoCover(MultipartFile videoCoverFile, Long id) {
        //按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("集次不存在");
        }
        //备份旧头像
        String oldVideoCover=episode.getCover();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(videoCoverFile);
        //根据用户主键修改用户头像
        episode.setCover(filename);
        if (mapper.update(episode) <= 0) {
            throw new ServiceException("摘要更新失败：DB操作异常");
        }
        try {
            //从MinIO中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO_COVER.equals(oldVideoCover)) {
                MinioUtil.delete(oldVideoCover, ML.Minio.EPISODE_VIDEO_COVER_DIR, ML.Minio.BUCKET_NAME);
            }
                //向MinIO中上传新头像
                MinioUtil.upload(videoCoverFile, filename, ML.Minio.EPISODE_VIDEO_COVER_DIR, ML.Minio.BUCKET_NAME);

        } catch (Exception e) {
            throw new ServiceException("摘要更新失败：MinIo操作异常");
        }
        //返回文件名
        return new Result<>(filename);
    }


    @Override
    @CacheEvict(allEntries = true)
    public Result<String> uploadVideo(MultipartFile videoFile, Long id) {
        //按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("集次不存在");
        }
        //备份旧头像
        String oldVideo = episode.getVideo();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(videoFile);
        //根据用户主键修改用户头像
        episode.setVideo(filename);
        if (mapper.update(episode) <= 0) {
            throw new ServiceException("摘要更新失败：DB操作异常");
        }
        try {
            //从MinIO中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO.contains(oldVideo)) {
                MinioUtil.delete(oldVideo, ML.Minio.EPISODE_VIDEO_DIR, ML.Minio.BUCKET_NAME);
                //向MinIO中上传新头像
                MinioUtil.upload(videoFile, filename, ML.Minio.EPISODE_VIDEO_DIR, ML.Minio.BUCKET_NAME);
            }
        } catch (Exception e) {
            throw new ServiceException("封面更新失败：MinIo操作异常");
        }
        //返回文件名
        return new Result<>(filename);
    }
    @Override
    public List<EpisodeExcelDTO> excel() {
        //加一层递归深度，Episode->season->course->category
        RelationManager.setMaxDepth(4);
        //查询全部记录
        List<Episode> episodes = mapper.selectAllWithRelations();

        List<EpisodeExcelDTO> result =new ArrayList<>();
        episodes.forEach(episode -> {
            EpisodeExcelDTO episodeExcelDTO=BeanUtil.copyProperties(episode,EpisodeExcelDTO.class);
            //赋值Season相关信息
            Season season=episode.getSeason();
            episodeExcelDTO.setSeasonTitle(season.getTitle());
            episodeExcelDTO.setSeasonInfo(season.getInfo());

            Course course=season.getCourse();
            episodeExcelDTO.setCourseTitle(course.getTitle());
            episodeExcelDTO.setCourseInfo(course.getInfo());
            episodeExcelDTO.setPrice(course.getPrice());
            episodeExcelDTO.setAuthor(course.getAuthor());

            Category category=course.getCategory();
            episodeExcelDTO.setCategoryTitle(category.getTitle());
            result.add(episodeExcelDTO);
        });
        return result;
    }


}
